<template>
  <div>
    <!-- <keep-alive>
          <router-view></router-view>
    </keep-alive>-->
    <!-- <router-view></router-view> -->
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
    <storeRewardDialog ref="rewardDialog"></storeRewardDialog>
  </div>
</template>
<script>
import sync from "@/utils/sync";
// import service from "@/utils/service";
import { mapActions } from "vuex";
import { getClientId, wxAuth } from "@/utils/util";
import { setClientInfo } from "@/utils/auth";
import storeRewardDialog from "@/components/store-reward-dialog";
import { Dialog } from "vant";
import { getClient } from "@/utils/util";

import { isIOS } from "mobile-device-detect";
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      timer: null,
      isDownload: false
    };
  },
  components: {
    storeRewardDialog,
    [Dialog.Component.name]: Dialog.Component
  },

  created() {
    // 初始化APP配置信息
    this.getSysConfig();
    // 初始化获取用户信息
    if(getToken()){
       this.getUserInfo()
      .then(data => {
        sync.connect();
        this.getCartList();
         if (
          getClientId() == 3 &&
          !window.isWxAuthFlag
        ){
            let loc = window.location.href;
          	if (loc.indexOf('/login/register') != -1) {
              this.$router.push("/main/home/" + loc.substring(loc.indexOf('?')));
					}
        }
      })
      .catch(error => {
        if (
          getClientId() == 3 &&
          !this.$store.state.user.isLogin &&
          !window.isWxAuthFlag
        ) {
          // 微信中
          wxAuth();
        }
      });
    }else{
      if (
          getClientId() == 3 &&
          !this.$store.state.user.isLogin &&
          !window.isWxAuthFlag
        ) {
          // 微信中
          wxAuth();
        }
    }
  },
  mounted() {
    let me = this;
    // console.log(JSON.parse(JSON.stringify({"title":"标题","content":"内容","payload":"1"})).title)
    this.onPlusReady(() => {
      // console.log('version',plus.runtime.version);
      //   console.log('versionCode',plus.runtime.versionCode)
      let _this = this;
      document.addEventListener(
        "resume",
        function() {
          console.log("从后台切换到前台");
          if (!this.isDownload) {
            _this.getUpdateInfo();
          }
          //从后台切换到前台
        },
        false
      );

      this.getUpdateInfo();
      var first = null;
      var webview = plus.webview.currentWebview();
      plus.push.addEventListener(
        "click",
        function(msg) {
          let { payload } = msg;
          if (isIOS) {
            plus.push.addEventListener("click", function(msg) {
              //导入ios UIApplication
              var UIApplication = plus.ios.import("UIApplication");
              var app = UIApplication.sharedApplication();
              //获取应用图标的数量
              var oldNum = app.applicationIconBadgeNumber();
              var newNum = oldNum - 1;
             
              //设置应用图标的数量
              plus.runtime.setBadgeNumber(0);
              //导入个推原生类
              var GeTuiSdk = plus.ios.importClass("GeTuiSdk");
              GeTuiSdk.setBadge(newNum);
            });
          }
          if (typeof payload == "string") {
            payload = JSON.parse(payload);
          }

          if (payload.type == "CONFIRM") {
            me.$router.push("/msg/msgDetail/" + payload.orderId);
          } else {
            me.$router.push("/msg/visitMsg/" + msg.content);
          }
          //处理透传消息的业务逻辑代码
        },
        false
      );
      plus.push.addEventListener(
        "receive",
        function(msg) {
          // let payload = JSON.parse(msg.payload);
          // {"title":"标题","content":"内容","payload":"1","":1}
          console.log("进来了通知");
          console.log(msg);
          console.log(msg.payload);
          console.log(msg.payload.msgType);
          if (msg.payload.msgType == 1) {
            if (isIOS) {
              // let payload = JSON.parse(msg.payload);
              msg.payload.msgType = 0;
              plus.push.createMessage(
                msg.content,
                JSON.stringify(msg.payload),
                {
                  title: msg.title
                }
              );
            }
          }
          //处理透传消息的业务逻辑代码
        },
        false
      );

      plus.key.addEventListener("backbutton", function() {
        webview.canBack(function(e) {
          if (
            e.canBack &&
            !me.$route.path.includes("/main/") &&
            me.$route.path != "/"
          ) {
            if (!me.$route.path.includes("/goods/")) {
              webview.back(); //这里不建议修改自己跳转的路径
            }
          } else {
            if (
              me.$route.path == "/main/cart" &&
              me.$route.query.from == "detail"
            ) {
              webview.back(); // 购物车为从商详进入的就回退到详情
              return;
            }
            //首次按键，提示‘再按一次退出应用’
            if (!first) {
              first = new Date().getTime(); //获取第一次点击的时间戳
              // console.log('再按一次退出应用');//用自定义toast提示最好
              // toast('双击返回键退出应用'); //调用自己写的吐丝提示 函数
              plus.nativeUI.toast("再按一次退出应用", {
                duration: "short"
              }); //通过H5+ API 调用Android 上的toast 提示框
              setTimeout(function() {
                first = null;
              }, 1000);
            } else {
              if (new Date().getTime() - first < 1000) {
                //获取第二次点击的时间戳, 两次之差 小于 1000ms 说明1s点击了两次,
                plus.runtime.quit(); //退出应用
              }
            }
          }
        });
      });
    });
  },
  methods: {
    ...mapActions("cart", ["getCartList"]),
    ...mapActions("sys", ["getSysConfig"]),
    ...mapActions("user", ["getUserInfo"]),
    getUpdateInfo() {
      this.isDownload = true;
      this.$http
        .post("config/getAppVersion", { appType: "android" })
        .then(data => {
          let { mustUpdate, versionNum, url } = data.info;
          // console.log('url111')
          // console.log('version',version);
          // console.log('versionCode',versionCode)
          if (!versionNum) {
            return;
          }
          if (plus.runtime.version != versionNum && !isIOS) {
            if (mustUpdate == 0) {
              Dialog.confirm({
                title: "提示",
                message: "app有新的版本，现在更新吗？"
              })
                .then(() => {
                  plus.nativeUI.showWaiting(
                    `正在更新，大约需要3-5分钟，请稍后...`
                  );
                  var dtask = plus.downloader.createDownload(url, {}, function(
                    d,
                    status
                  ) {
                    this.isDownload = false;
                    // plus.nativeUI.showWaiting("正在更新...");
                    if (status == 200) {
                      // 下载成功
                      var path = d.filename;
                      plus.runtime.install(
                        path,
                        null,
                        () => {
                          // plus.nativeUI.alert("更新成功！");
                        },
                        () => {
                          plus.nativeUI.alert("更新失败！", () => {
                            if (mustUpdate == 0) {
                              plus.runtime.quit();
                            }
                          });
                        }
                      );
                    } else {
                      //下载失败
                      plus.nativeUI.alert("网络错误,更新失败！");
                    }
                    plus.nativeUI.closeWaiting();
                    clearInterval(this.timer);
                  });
                  dtask.start();
                })
                .catch(() => {
                  // on cancel
                  this.isDownload = false;
                });
            } else {
              Dialog.confirm({
                title: "提示",
                message: "app有新的版本,需更新后才能使用。"
              })
                .then(() => {
                  plus.nativeUI.showWaiting(
                    `正在更新，大约需要3-5分钟，请稍后...`
                  );
                  var dtask = plus.downloader.createDownload(url, {}, function(
                    d,
                    status
                  ) {
                    // plus.nativeUI.showWaiting("正在更新...");
                    if (status == 200) {
                      // 下载成功
                      var path = d.filename;
                      plus.runtime.install(
                        path,
                        null,
                        () => {
                          // plus.nativeUI.alert("更新成功！");
                        },
                        () => {
                          plus.nativeUI.alert("更新失败！", () => {
                            if (mustUpdate == 0) {
                              plus.runtime.quit();
                            }
                          });
                        }
                      );
                    } else {
                      //下载失败
                      plus.nativeUI.alert("网络错误,更新失败！");
                    }
                    plus.nativeUI.closeWaiting();
                    clearInterval(this.timer);
                    this.isDownload = false;
                  });
                  dtask.start();
                })
                .catch(() => {
                  console.log("catch");
                  plus.runtime.quit();
                  this.isDownload = false;
                  // on cancel
                });
            }
          }
        })
        .catch(() => {
          this.isDownload = false;
        });
    },
    downloadAPK() {
      plus.nativeUI.showWaiting(`正在更新，大约需要3-5分钟，请稍后...`);
      var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
        // plus.nativeUI.showWaiting("正在更新...");
        if (status == 200) {
          // 下载成功
          var path = d.filename;
          plus.runtime.install(
            path,
            null,
            () => {
              // plus.nativeUI.alert("更新成功！");
            },
            () => {
              plus.nativeUI.alert("更新失败！", () => {
                if (mustUpdate == 0) {
                  plus.runtime.quit();
                }
              });
            }
          );
        } else {
          //下载失败
          plus.nativeUI.alert("网络错误,更新失败！");
        }
        plus.nativeUI.closeWaiting();
        clearInterval(this.timer);
      });
      dtask.start();
    }
  }
};
</script>
<style lang="scss" src="./assets/scss/global.scss" />